package com.atguigu.test.mvc.my;

import com.atguigu.test.mvc.annotation.Yaml;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * @author zp
 * @version 1.0
 * @description: 自定义返回值处理器 专门处理@Yaml注解
 * @date 2023/1/2 16:28
 */
public class MyYamlHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.hasMethodAnnotation(Yaml.class);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        // 获取转化的字符串
        String dump = new org.yaml.snakeyaml.Yaml().dump(returnValue);
        // 获取http的返回
        HttpServletResponse httpServletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
        // 设置返回格式和字符编码
        httpServletResponse.setContentType("text/plain;charset=utf-8");
        httpServletResponse.getWriter().println(dump);
        // 设置请求已经完毕
        mavContainer.setRequestHandled(true);
    }
}
